package ws.jonas.sybosc.db;

import java.sql.SQLException;

import ws.jonas.sybosc.gui.LogPanel;

public class DBConnection {
	private SqlDb sql;
	private final ConnectionCallback callback;

	public DBConnection(ConnectionCallback callback) {
		if (callback == null) {
			throw new NullPointerException("callback");
		}
		this.callback = callback;
	}

	public void connect(DBConfig config) throws SQLException {
		String vendor = config.getVendor();
		String host = config.getHost();
		String user = config.getUser();
		String password = config.getPassword();
		if (host == null) {
			throw new IllegalArgumentException("Must specify host");
		}
		if ("mysql".equalsIgnoreCase(vendor)) {
			sql = new MysqlDb(host, user, password);
		} else if ("mssql".equalsIgnoreCase(vendor)) {
			sql = new MssqlDb(host, user, password);
		} else {
			throw new IllegalArgumentException("Unkown vendor: " + vendor);
		}
		callback.onConnect();
	}

	public void disconnect() throws SQLException {
		if (sql != null) {
			sql.close();
			callback.onDisconnect();
		}
	}

	public boolean isOnline() {
		try {
			return sql != null && !sql.isClosed();
		} catch (SQLException e) {
			LogPanel.getInstance().println(e);
			return false;
		}
	}

	public SqlDb getDb() {
		return sql;
	}

	public interface ConnectionCallback {
		public void onConnect();
		public void onDisconnect();
	}
}
